package com.juyu.miliao.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

public class SumAgeUtil {

    private static final int DEFAULT_AGE = 18;

	private final static Logger logger = LoggerFactory.getLogger(SumAgeUtil.class);

	public static int getAgeByBirth(LocalDate birthday) {
		ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = birthday.atStartOfDay(zoneId);
        Date date = Date.from(zdt.toInstant());
        int age = DEFAULT_AGE;
		try {
			Calendar now = Calendar.getInstance();
			now.setTime(new Date());// 当前时间

			Calendar birth = Calendar.getInstance();
			birth.setTime(date);

            // 如果传入的时间，在当前时间的后面，返回18岁
            if (!birth.after(now)) {
				age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
				if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
					age += 1;
				}
			}

		} catch (Exception e) {// 兼容性更强,异常后返回数据
			logger.error("计算年龄发送错误：参数-"+birthday,e);
		}
        return age;
	}
}
